import { createRouter, createWebHashHistory } from "vue-router";
import useUserStore from "@/stores/user";
// @是vue中一个标识，这是标识是一个路径，指向src文件夹

const routes = [
  {
    path: "/reg",
    component: () => import("@/views/reg/index.vue"),
  },
  {
    path: "/login",
    component: () => import("@/views/login/index.vue"),
  },
  {
    path: "/",
    component: () => import("@/views/index/index.vue"),
    redirect: "/home",
    children: [
      {
        path: "home",
        component: () => import("@/views/home/index.vue"),
      },
      {
        path: "user-info",
        component: () => import("@/views/user/userInfo.vue"),
      },
      {
        path: "user-avatar",
        component: () => import("@/views/user/userAvatar.vue"),
      },
      {
        path: "user-pwd",
        component: () => import("@/views/user/userPwd.vue"),
      },
      {
        path: "art-cate",
        component: () => import("@/views/article/artCate.vue"),
      },
    ],
  },
];

const router = createRouter({
  history: createWebHashHistory(import.meta.env.BASE_URL),
  routes,
});

// 路由前置守卫：进入任何一个组件都会经过路由前置守卫
// to:要去的组件
// from:从哪个组件来的
// next: 三种形式  next()放行   next(false)不放行   next(路径)跳转该路径

// 后台管理系统中两个页面不需要token,分别是登录与注册
const whiteList = ["/reg", "/login"];
router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const token = userStore.token;

  // 去登录或注册页
  if (whiteList.includes(to.path)) {
    // 有token,不去
    if (token) {
      next(false);
    } else {
      // 没有token,可以去
      next();
    }
  } else {
    // 不是去登录或注册页
    if (token) {
      next(); //放行
    } else {
      next("/login"); //去登录页
    }
  }
});

export default router;
